import 'package:casdon/modules/demo/domain/states/demo_camera_state.dart';
import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:camera/camera.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';

final cameraControllerProvider =
    StateNotifierProvider<CameraControllerNotifier, DemoCameraState>(
      (ref) => CameraControllerNotifier(),
    );

class CameraControllerNotifier extends StateNotifier<DemoCameraState> {
  CameraControllerNotifier() : super(DemoCameraState());

  List<CameraDescription> _cameras = [];

  Future<void> initCamera() async {
    if (state.initialized) return;
    if (!mounted) return;
    _cameras = await availableCameras();
    if (_cameras.isEmpty) {
      print("❌ No cameras found.");
      return;
    }
    if (!mounted) return;
    final controller = CameraController(
      _cameras.first,
      ResolutionPreset.medium,
      enableAudio: false,
    );
    if (!mounted) return;
    await controller.initialize();
    state = state.copyWith(controller: controller, initialized: true);
  }

  @override
  void dispose() {
    state.controller?.dispose();
    super.dispose();
  }

  Future<void> toggleTorch() async {
    final controller = state.controller;
    if (controller == null) return;
    final newTorchState = state.torchOn ? FlashMode.off : FlashMode.torch;
    await controller.setFlashMode(newTorchState);
    state = state.copyWith(torchOn: !state.torchOn);
  }

  Future<XFile?> pickImage() async {
    final picker = ImagePicker();

    final image = await picker.pickImage(source: ImageSource.gallery);
    if (image != null) {
      final compressedImage = await compressImage(image);
      state = state.copyWith(pickedImage: compressedImage);
    }
    return image;
  }

  Future<XFile?> takePicture() async {
    final controller = state.controller;
    if (controller == null || controller.value.isInitialized == false) {
      return null;
    }

    try {
      final picture = await controller.takePicture();
      final compressedImage = await compressImage(picture);
      state = state.copyWith(pickedImage: compressedImage);

      print("拍照路径: ${state.pickedImage!.path}");
      return picture;
    } catch (e) {
      print("拍照失败: $e");
      return null;
    }
  }

  Future<XFile?> compressImage(XFile file) async {
    int sizeInBytes = await file.length(); // 获取文件字节大小
    double sizeInKB = sizeInBytes / 1024;

    print('文件大小: ≈ ${sizeInKB.toStringAsFixed(2)} KB');

    final dir = await getTemporaryDirectory();
    final targetPath =
        "${dir.path}/${DateTime.now().millisecondsSinceEpoch}.${file.path.split('.').last}";

    var result = await FlutterImageCompress.compressAndGetFile(
      file.path,
      targetPath,
      quality: 40, // 压缩质量 0~100
      minHeight: 1024,
      minWidth: 1024,
    );
    final xfile = XFile(result!.path);
    int sizeInBytes2 = await xfile.length(); // 获取文件字节大小
    double sizeInKB2 = sizeInBytes2 / 1024;

    print('压缩后文件大小: ≈ ${sizeInKB2.toStringAsFixed(2)} KB');
    return xfile;
  }

  void onLifecycleChanged(AppLifecycleState lifecycle) {
    final controller = state.controller;
    if (controller == null) return;

    switch (lifecycle) {
      case AppLifecycleState.inactive:
        controller.pausePreview();
        break;
      case AppLifecycleState.paused:
        controller.pausePreview();
        break;
      case AppLifecycleState.resumed:
        if (!controller.value.isInitialized) {
          initCamera();
        }
        break;
      default:
        break;
    }
  }
}
